package com.m7788.screen;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.m7788.po.UploadInfo;
import com.m7788.po.UploadProData;
import com.m7788.util.AppUtil;
import com.m7788.util.Constant;
import com.m7788.view.UmengBaseActivity;
import com.tool.utils.DataUtil;

public class TakePhotoScreen extends UmengBaseActivity implements OnClickListener {
	Button submit, takePhoto, btn_return,btn_roll,btn_list;
	ImageView image1;
	/**
	 * 调用手机拍照
	 */
	private static final int DO_CAMERA = 1234;
	private static final int DO_CUSTOM_CAMERA = 1236; 
	String account;
	File file;
	
	private String type;//动作类型
	private String params;//参数集合
	Map<String, String> parmasMap;
	private String Oper;//判断来源
	private String wapFrom;
	ArrayList<UploadInfo> infoList;
	UploadProData proData;
	CommandReceiver cmdReceiver;
	int canTemp=0;
	int curing=0;
	boolean openCamera = false;
	String imagePath="";
	 private class CommandReceiver extends BroadcastReceiver{
	       @Override
	       public void onReceive(Context context, Intent intent) {
	        if(intent.getAction().equals(Constant.ACTION_STOA)){
	        	   Bundle bundle = intent.getExtras();
		    	   int operation = bundle.getInt("operation",-1);
//		    	   String  desc = bundle.getString("desc");
		    	   if(operation==1){//
		    		   finish();
		    	   }else  if(operation==2){
		    		   finish();
		    	   }
	                 
	          }
	       }                        
	   }
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.take_photo_screen);		
		initDBdata();
		initView();
		
		cmdReceiver = new CommandReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.ACTION_STOA);
        registerReceiver(cmdReceiver, filter);
       
	}
	@Override
	protected void onDestroy() {
    	AppUtil.saveRecord(TakePhotoScreen.this,Constant.PARAMS,"");
		this.unregisterReceiver(cmdReceiver);
		super.onDestroy();
	}
	@Override
	protected void onResume() {
		super.onResume();
		if(AppUtil.isUploadList(this)){
			btn_list.setVisibility(View.VISIBLE);
		}else{
			btn_list.setVisibility(View.GONE);
		}
	}
	/**
	 * 
	 * 方法名：initView 
	 * 功能:初始化界面 
	 * 参数： 
	 * 创建人：huanghsh 
	 * 创建时间：2012-6-3
	 */
	private void initView() {
		image1 = (ImageView) findViewById(R.id.tps_iv_image1);

		submit = (Button) findViewById(R.id.tps_btn_submit);
		submit.setOnClickListener(this);
		takePhoto = (Button) findViewById(R.id.tps_btn_camera);
		takePhoto.setOnClickListener(this);
		btn_list = (Button) findViewById(R.id.tps_btn_list);
		btn_list.setOnClickListener(this);
		doTakePhoto();
//		doTakePhotoCustom();
	}

	private void initDBdata(){
    	Oper = AppUtil.getRecord(TakePhotoScreen.this,Constant.OPERATION);
		type =AppUtil.getRecord(TakePhotoScreen.this,Constant.TYPE);
		params =AppUtil.getRecord(TakePhotoScreen.this,Constant.PARAMS);
		wapFrom = AppUtil.getRecord(TakePhotoScreen.this,Constant.FROM);
		if(params.length()>0){
			parmasMap = AppUtil.combineHttpParams(params);
		}
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.tps_btn_roll:
			break;
		case R.id.tps_btn_submit:
			doTakePhoto() ;
			break;
		case R.id.tps_btn_camera:
			doTakePhoto();
			break;
		case R.id.tps_btn_list:
    		Intent intent2 = new Intent(TakePhotoScreen.this, UploadInfoScreen.class);
			startActivity(intent2);
    		break;

		}

	}

	/**
	 * 
	 * 方法名：doTakePhoto 功能：相机拍摄 参数： 创建人：huanghsh 创建时间：2012-6-3
	 */
	private void doTakePhoto() {
		try {
			
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			////////////////////
			//保存到自定义路径
			if(!new File(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+ "7788").exists()){
				new File(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+ "7788").mkdirs();
			}
			File baseFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+ "7788");  
	        String fileName = new Date().getTime()+".jpg";  // 文明名  
	        File imgFile = new File(baseFile, fileName);  //保存图片的路径  
	        imagePath = imgFile.getAbsolutePath();
	        intent.putExtra(MediaStore.EXTRA_OUTPUT,  
	                Uri.fromFile(imgFile));  
		    //////////////////////
			startActivityForResult(intent, DO_CAMERA);

		} catch (ActivityNotFoundException e) {
			Toast.makeText(this, "调用不到拍照程序", Toast.LENGTH_SHORT).show();
		}
	}

	private void doTakePhotoCustom() {  
        try {  
        	Intent getImageByCamera = new Intent(this,CustomCamera.class);
        	startActivityForResult(getImageByCamera,DO_CUSTOM_CAMERA);

        } catch (ActivityNotFoundException e) {  
            Toast.makeText(this, "调用不到拍照程序",  
                    Toast.LENGTH_LONG).show();  
        }  
    }
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		int maxSize=0;
		if (requestCode == DO_CAMERA && resultCode == RESULT_OK) {
			data = null;
			if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
                Intent mediaScanIntent = new Intent(
                        Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri contentUri = Uri.fromFile(new File(imagePath)); //out is your output file
                mediaScanIntent.setData(contentUri);
                sendBroadcast(mediaScanIntent);
            } else {
            	sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"    
	                    + Environment.getExternalStorageDirectory())));    
            }
//			int degree = AppUtil.readPictureDegree(imagePath);
	          AppUtil.saveRecord(TakePhotoScreen.this, Constant.SinglePhoto, imagePath);
//	          AppUtil.saveRecord(TakePhotoScreen.this, Constant.SINGLE_DEGREE, ""+degree);
	          Intent intent = new Intent(TakePhotoScreen.this, SinglePhotoScreen.class);
	          intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
				 startActivity(intent);
				 finish();
				 
				 
//			boolean isCan = true;
//			openCamera = true;
//			Bundle bundle = data.getExtras();
//			if(bundle!=null){
//				gbitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
//				sendToSingle();
//				Log.e("系统拍照获取图片长宽",gbitmap.getHeight()+"--"+gbitmap.getWidth());
//				Intent intent = new Intent(TakePhotoScreen.this, SinglePhotoScreen2.class);
//				intent.putExtras(bundle);
//				  startActivity(intent);
//			      finish();
//				proData = new UploadProData();
//				infoList = new ArrayList<UploadInfo>();
//	    		if("2".equals(Oper)){
//					String id = dbUtil.getRecord(Constant.sid);
//					String pid = dbUtil.getRecord(Constant.Tpid); 
//					String url = dbUtil.getRecord(Constant.URL_UPLOAD); 
//					parmasMap = new HashMap<String, String>();
//					parmasMap.put("id", id);
//					parmasMap.put("p_id", pid);
//					parmasMap.put("url", url);
//					parmasMap.put("name", Constant.DefaultFileName);
//				}else  if("1".equals(Oper) && params.length()>0){//来自网络
//						parmasMap = AppUtil.combineHttpParams(params);
//						String fnum = parmasMap.get("num");
//						String fmax = parmasMap.get("max_num");
//						String name = AppUtil.UnicodeToGB2312(parmasMap.get("name"));
//						String maxTemp = parmasMap.get("maxsize");
//						if(maxTemp!=null&& maxTemp.length()>0){
//							maxSize = Integer.valueOf(maxTemp);
//						}
//						if(fnum!=null && fmax!=null){
//							int re = Integer.valueOf(fmax)-Integer.valueOf(fnum)-canTemp;
//							if(re==0){
//								DataUtil.showShortToast(getApplicationContext(), "文件夹："+name+"图片数量已满，无法上传");
//								isCan = false;
//								finish();
//							}
//						}
//						
//						String cuurimg=parmasMap.get("cuurimg");
//						if(cuurimg!=null && cuurimg.length()>0){
//							int temp = Integer.valueOf(cuurimg);
//							temp=temp+1+curing;
//							parmasMap.put("cuurimg", temp+"");
//						}
//				}
//	    		parmasMap.put("fName", new Date().getTime()+"");
//	    		if(isCan){
//					File file = ImageUpload.getInstance(this.getApplicationContext()).formatFileFromBitmap(gbitmap,maxSize);
//					File sfile = ImageUpload.getInstance(this.getApplicationContext()).formatFileFromBitmapSmall(gbitmap);
//					
//					UploadInfo info = new UploadInfo();
//					info.setParmasMap(parmasMap);
//					info.setFile(file);
//					info.setSmallFile(sfile);
//					infoList.add(info);
//					proData.setInfoList(infoList);
//		    		proData.setTotal(infoList.size());
//		    		proData.setDate(DateUtil.formatDateTimeByDate(new Date()));
//		    		proData.setCur(0);
//		    		proData.setFailNum(0);
//		    		proData.setFileName(AppUtil.UnicodeToGB2312(parmasMap.get("name")));
//		    		if("2".equals(type)){
//						proData.setType("修改");
//					}else{
//						proData.setType("上传");
//					}
//		    		ImageUpload.getInstance(this.getApplicationContext()).sendImage(proData,new Long(0));
//		    		canTemp++;
//		    		curing++;
//		    		finish();
//			}else{
//				DataUtil.showShortToast(TakePhotoScreen.this, bundle+",照相机返回无数据");
//				finish();
//			}
			
		}else if (requestCode == DO_CUSTOM_CAMERA && resultCode == RESULT_OK) {
//			 	boolean isCan = true;
//				openCamera = true;
//				Bundle bundle2 = data.getExtras();
//				if(bundle2!=null){
//					String imagePath = data.getExtras().getString("path");
//					
//					
//					
//					
//					
////					gbitmap = (Bitmap) bundle2.get("data");
//					proData = new UploadProData();
//					infoList = new ArrayList<UploadInfo>();
//		    		if("1".equals(Oper) && params.length()>0){//来自网络
//							parmasMap = AppUtil.combineHttpParams(params);
//							String fnum = parmasMap.get("num");
//							String fmax = parmasMap.get("max_num");
//							String maxTemp = parmasMap.get("maxsize");
//							if(maxTemp!=null&& maxTemp.length()>0){
//								maxSize = Integer.valueOf(maxTemp);
//							}
//							String name = AppUtil.UnicodeToGB2312(parmasMap.get("name"));
//							if(fnum!=null && fmax!=null){
//								int re = Integer.valueOf(fmax)-Integer.valueOf(fnum)-canTemp;
//								if(re==0){
//									DataUtil.showShortToast(getApplicationContext(), "文件夹："+name+"图片数量已满，无法上传");
//									isCan = false;
//									finish();
//								}
//							}
//							
//							String cuurimg=parmasMap.get("cuurimg");
//							if(cuurimg!=null && cuurimg.length()>0){
//								int temp = Integer.valueOf(cuurimg);
//								temp=temp+1+curing;
//								parmasMap.put("cuurimg", temp+"");
//							}
//					}
//		    		parmasMap.put("fName", new Date().getTime()+"");
//		    		if(isCan){
////						File file = ImageUpload.getInstance(this.getApplicationContext()).formatFileFromBitmap(gbitmap);
////						File sfile = ImageUpload.getInstance(this.getApplicationContext()).formatFileFromBitmapSmall(gbitmap);
//						File file = ImageUpload.getInstance().readFromUri(imagePath,0,maxSize);
//						File sfile = ImageUpload.getInstance().readFromUriSmall(imagePath,0);
//						
//						UploadInfo info = new UploadInfo();
//						info.setParmasMap(parmasMap);
//						info.setFile(file);
//						info.setSmallFile(sfile);
//						infoList.add(info);
//						proData.setInfoList(infoList);
//			    		proData.setTotal(infoList.size());
//			    		proData.setDate(DateUtil.formatDateTimeByDate(new Date()));
//			    		proData.setCur(0);
//			    		proData.setFailNum(0);
//			    		proData.setFileName(AppUtil.UnicodeToGB2312(parmasMap.get("name")));
//			    		if("2".equals(type)){
//							proData.setType("修改");
//						}else{
//							proData.setType("上传");
//						}
//			    		ImageUpload.getInstance().sendImage(proData,new Long(0));
//			    		canTemp++;
//			    		curing++;
//			    		finish();
//		    		}
//				}
		}else{
			finish();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	

	/**
	 * 
	 * 
	 * 类名称：UploadAsyncTask 类描述： 异步上传图片 创建人： huanghsh 创建时间：2012-6-7 修改人：huanghsh
	 * 修改时间：2012-6-7 修改备注：
	 * 
	 * @version
	 * 
	 */
	private class UploadAsyncTask extends AsyncTask<Object, Object, Object> {
		@Override
		protected void onPostExecute(Object result) {
			if(result!=null&&result.toString().length()>0){
				String json = result.toString();
				  try {
					String ret = new JSONObject(json).getString("ret");
					if("0".equals(ret)){
						DataUtil.showShortToast(TakePhotoScreen.this, "数据异常，请重新上传");
					
					} else if("1".equals(ret)){
						String code = new JSONObject(json).getString("result");
						String desc = new JSONObject(json).getString("desc");
						if("0".equals(code)){
							DataUtil.showShortToast(TakePhotoScreen.this, "上传失败"+desc);
						}else if("1".equals(code)){
							
							DataUtil.showShortToast(TakePhotoScreen.this, "上传成功");
						}else if("2".equals(code)){
						   DataUtil.showShortToast(TakePhotoScreen.this, "上传失败，登录已过期，请重新登录");
			    		   Intent intent2 = new Intent(TakePhotoScreen.this, LoginScreen.class);
			    		   intent2.putExtra("key", "changeUser");
			    		   TakePhotoScreen.this.startActivity(intent2);
						}
						
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}	
			}
			super.onPostExecute(result);
		}

		@Override
	 protected Object doInBackground(Object... params) {
//			HttpService.context=TakePhotoScreen2.this;
//			for(UploadInfo info:infoList){
////		 	String result = HttpService.uploadPicture(AppUtil.getUserAgent(TakePhotoScreen2.this),info);
//			}
			return null;
	 }
	}

	
	
	
	
}
